<?php

namespace app\admin\model\goods;

use think\Model;
use traits\model\SoftDelete;

class Goods extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'goods';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text'
    ];

	public static function init(){
		self::beforeWrite(function($row){
			if(isset($row['sku']) && $row['sku']){
				$sku = json_decode($row['sku'], true);
				if(is_array($sku)){
					$productModel = new Product();
					foreach($sku as $k=>&$v){
						$product = $productModel->find($v['product_id']);
						$v['product'] = $product['name'];
						$v['product_title'] = $product['title'];
					}
				}
			}
			$row->sku = json_encode($sku);
		});
	}
    
    public function getStatusList()
    {
        return ['normal' => __('Normal'), 'hidden' => __('Hidden'), 'pulloff' => __('Pulloff')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

	public function category(){
		return $this->hasOne('app\admin\model\goods\Category', 'id', 'category_id');
	}


}
